﻿#include "sysusermsgcontroller.h"
#include "utils/dictionaryutil.h"


SysUserMsgController::SysUserMsgController()
{
    m_pHelper = SqlHelper::instance();
    m_mapFunc.insert("/func/message/user/newmsg",   &SysUserMsgController::newmsg);     //获取系统未读消息
    m_mapFunc.insert("/func/message/user/detail",   &SysUserMsgController::detail);     //获取用户消息明细
    m_mapFunc.insert("/func/message/user/datagrid", &SysUserMsgController::datagrid);   //获取用户消息列表
    m_mapFunc.insert("/func/message/user/delete",   &SysUserMsgController::del);        //删除用户系统消息
    m_mapFunc.insert("/func/message/user/read",     &SysUserMsgController::read);       //已读用户消息
    m_mapFunc.insert("/func/message/user/readall",  &SysUserMsgController::readAll);    //全部已读用户消息
}

void SysUserMsgController::service(HttpRequest& request, HttpResponse& response)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QString access_token = request.getParameter("access_token");
    QString username = JwtUtil::getUsername(access_token);
    if(username == NULL || username.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    SysUser visitUser;
    if(!m_pHelper->selectUserByName(visitUser, username))
    {
        ret.failedMsg(QStringLiteral("用户不存在，操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QByteArray path = request.getPath().toLower();
    if(m_mapFunc.contains(path))
    {
        pServFunc func = m_mapFunc.value(path);
        (this->*func)(request, response, visitUser);
    }
}

//获取用户未读消息
// POST /func/message/user/newmsg
// {"code": 0, "msg": "", "data": {  "newmsg": 3} }
//{"code":0,"success":true,"msg":"操作成功","data":null}
void SysUserMsgController::newmsg(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, false, QStringLiteral("操作成功"));
    QList<SysUserMessage> userMsgList;
    QStringList condi;
    condi << "user_id=" + QString::number(visitUser.getId()) ;
    condi << QString("delete_status='%1'").arg(SysUserMessage::Delete_No) ;
    condi << QString("read_status='%1'").arg(SysUserMessage::Read_No) ;
    m_pHelper->getSysUserMessageList(userMsgList, condi, "public_time", false);

    if(userMsgList.size() > 0)
    {
        ret.setSuccess(true);
        ret.setData("newmsg", userMsgList.size());
    }
    ResponseUtil::replyJson(response, ret);
}

//获取用户消息明细
//http://localhost:9004/demo/func/message/user/detail?id=&access_token=
//{"code":0,"data":{"content":"ferf","createDate":1576726360000,"createName":"system","deleteStatus":"0","id":"","publicTime":1576726360000,"readStatus":"1","sysMessageId":"","title":"ef","type":"1","updateDate":1576735512000,"updateName":"admin","userId":"","versions":2},"msg":""}
void SysUserMsgController::detail(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral(""));
    QString idParam = request.getParameter("id");

    if(idParam.isEmpty())
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }
    int id = idParam.toInt();

    SysUserMessage msg;
    msg.setId(id);
    if(!m_pHelper->selectEntityById(&msg))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    msg.setReadStatus(QString::number(SysUserMessage::Read_Yes));
    if(!m_pHelper->updateEntity(&msg))
    {
        ret.failedMsg(QStringLiteral("操作失败"));
        ResponseUtil::replyJson(response, ret);
        return;
    }

    QJsonObject obj = msg.toJson();
    ret.setData(obj);

    ResponseUtil::replyJson(response, ret);
}

//获取用户消息列表
//http://localhost:9004/demo/func/message/user/datagrid?page=1&limit=20&field=publicTime&order=desc&access_token=
//{"code":0,"count":3,"data":[{"content":"滴答滴答滴答滴答滴","createDate":1578118183000,"createName":"system","deleteStatus":"0","id":"","publicTime":1578118183000,"readStatus":"1","sysMessageId":"3b2802231b220b26c8172da799aa9b4e","title":"大豆纤维","type":"系统消息","updateDate":1578118396000,"updateName":"admin","userId":"d4f2018bfc34b5c92942abebff2a829f","versions":6},{"content":"服务范围付多付付付付付付付付付付付vvvvv","createDate":1578109861000,"createName":"system","deleteStatus":"0","id":"fd89fb376002614e213b539b1edec0ec","publicTime":1578109861000,"readStatus":"1","sysMessageId":"4d9451e317c0c4a8830eb1524968c06c","title":"废物范文芳","type":"系统消息","updateDate":1578113511000,"updateName":"admin","userId":"d4f2018bfc34b5c92942abebff2a829f","versions":2},{"content":"dewdwe","createDate":1576736618000,"createName":"system","deleteStatus":"0","id":"","publicTime":1576736618000,"readStatus":"1","sysMessageId":"","title":"deww","type":"系统消息","updateDate":1576736628000,"updateName":"admin","userId":"","versions":15}],"msg":""}
void SysUserMsgController::datagrid(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{

    int page = 1;
    int limit = 30;
    QString field = "publicTime";
    QString order = "desc";

    if(request.getParameterMap().contains("page"))
    {
        page = request.getParameter("page").toInt();
    }
    if(request.getParameterMap().contains("limit"))
    {
        limit = request.getParameter("limit").toInt();
    }
    if(request.getParameterMap().contains("field"))
    {
        field = request.getParameter("field");
    }
    if(request.getParameterMap().contains("order"))
    {
        order = request.getParameter("order");
    }

    QStringList condi;
    QList<SysUserMessage> msgList;
    condi << QString("delete_status = '%1'").arg(SysUserMessage::Delete_No);
    int count = 0;
    m_pHelper->getSysUserMessageList(msgList,  count, page, limit, condi, field, order=="asc");

    QMap<QString, QString> mapType = DictionaryUtil::instance()->getDictionary("func_sys_message_type");

    QJsonArray dataArray;
    foreach (SysUserMessage msg, msgList) {
        QJsonObject obj = msg.toJson();

        foreach (QString key, mapType.keys()) {
            if(mapType[key] == msg.getType())
            {
                obj.insert("type",  key);
                break;
            }
        }
         dataArray.append(obj);
    }

    ResultJson ret(0, true, QStringLiteral(""));
    ret.setProp("count", msgList.size());
    ret.setData(dataArray);
    ResponseUtil::replyJson(response, ret);
}
//删除用户系统消息
void SysUserMsgController::del(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    //用户消息ids集合
    QString ids = request.getParameter("ids");
    QStringList idList = ids.split(",");
    for(int i=0; i < idList.size(); i++)
    {
        QString userMsgId = idList.at(i);
        SysUserMessage msg;
        msg.setId(userMsgId.toInt());
        if(!m_pHelper->selectEntityById(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            continue;
        }
        msg.setDeleteStatus(QString::number(SysUserMessage::Delete_Yes));
        if(!m_pHelper->updateEntity(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            break;
        }
    }

    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam = request.getParameterJson();
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::DEL, QStringLiteral("删除用户消息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("删除用户消息成功"));
    m_pHelper->insertEntity(&log);
}
//已读用户消息
//http://localhost:9004/demo/func/message/user/read
//ids:
//{"code":0,"success":true,"msg":"操作成功","data":null}
void SysUserMsgController::read(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));

    //用户消息ids集合
    QString ids = request.getParameter("ids");
    QStringList idList = ids.split(",");
    for(int i=0; i < idList.size(); i++)
    {
        QString userMsgId = idList.at(i);
        SysUserMessage msg;
        msg.setId(userMsgId.toInt());
        if(!m_pHelper->selectEntityById(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            continue;
        }
        msg.setReadStatus(QString::number(SysUserMessage::Read_Yes));
        if(!m_pHelper->updateEntity(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            break;
        }
    }
    ResponseUtil::replyJson(response, ret);
    QJsonObject objParam;
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::UPDATE, QStringLiteral("已读用户消息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("已读用户消息完成"));
    m_pHelper->insertEntity(&log);
}
//全部已读用户消息
void SysUserMsgController::readAll(HttpRequest& request, HttpResponse& response, SysUser& visitUser)
{
    ResultJson ret(0, true, QStringLiteral("操作成功"));
    QList<SysUserMessage> userMsgList;
    QStringList condi;
    condi << "user_id=" + QString::number(visitUser.getId()) ;
    condi << QString("delete_status='%1'").arg(SysUserMessage::Delete_No) ;
    condi << QString("read_status='%1'").arg(SysUserMessage::Read_No) ;
    m_pHelper->getSysUserMessageList(userMsgList, condi, "public_time", false);

    foreach (SysUserMessage msg, userMsgList) {
        msg.setReadStatus(QString::number(SysUserMessage::Read_Yes));
        if(!m_pHelper->updateEntity(&msg))
        {
            ret.failedMsg(QStringLiteral("操作失败"));
            break;
        }
    }
    ResponseUtil::replyJson(response, ret);

    QJsonObject objParam;
    objParam.insert("access_token", "?");
    SysLog log("system", SysLog::UPDATE, QStringLiteral("全部已读用户消息"),
               visitUser.getUserName(),
                QString(__FILE__),
                QString(__FUNCTION__),
                GlobalFunc::JsonToString(objParam),
                request.getPeerAddress().toString(),
                request.getHeader("User-Agent"),
                QStringLiteral("全部已读用户消息完成"));
    m_pHelper->insertEntity(&log);
}
